#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <cstdlib>//-------------等于stdlib.h
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>

#define NUM 1024
#define N 2
using namespace std;

void wirter(int wfd)
{
    string s="hello, i am child!";
    pid_t self=getpid();
    int number=0;

    char buffer[NUM];
    while(true)
    {
        //构建发送字符串
        buffer[0]=0;//----------疑问-------字符串清空,提醒阅读代码的人,我把这个数组当字符串用了
        snprintf(buffer,sizeof(buffer),"%s-%d-%d",s.c_str(),self,number);
        cout<<buffer<<endl;
        //发送/写入给父进程----向管道中写入
        write(wfd,buffer,strlen(buffer));//-----------不用\0,文件不识别\0
        number++;
        sleep(1);
    }
}

void reader(int rfd)
{
    char buffer[NUM];
    while(true)
    {
        buffer[0]=0;
        ssize_t n =read(rfd,buffer,sizeof(buffer));//这里为什么是sizeof(buffer)?期望把这个buffer缓冲区读取,如果没满呢?
        if(n>0)
        {
            buffer[n]=0;//-------这里的0就是\0
            cout<<"father get a message["<<getpid()<<"]#"<<buffer<<endl;
        }
        else if(n==0)
        {
            break;
        }
        else break;
    }
}


int main()
{
    int pipefd[N]={0};
    int n=pipe(pipefd);
    //pipe失败
    if(n<0) return 1;

    //子写入,父读取
    pid_t id=fork();//------------------数据类型是pid_t 变量名是id(pid)
    if(id<0)
    {
        return 2;
    }
    else if(id==0)//------------------返回值对应是父进程还是子进程
    {
        //子进程
        close(pipefd[0]);

        //IPC code
        wirter(pipefd[1]);

        close(pipefd[1]);
        exit(0);//-------------------------进程退出exit();
    }
    else
    {
        //父进程
        close(pipefd[1]);

        //IPC code
        reader(pipefd[0]);

        pid_t rid=waitpid(id,nullptr,0);//-------------等待子进程结束,回收子进程
        if(rid<0)
        {
            return 3;
        }

        close(pipefd[0]);
    }
    return 0;
}